package principal;

import base.Solucao;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class TelaPrincipal extends javax.swing.JFrame {

    private File arquivoSelecionado;
    private final TelaParametros telaParametros;

    public TelaPrincipal() {
        initComponents();
        telaParametros = new TelaParametros();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser = new javax.swing.JFileChooser();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea = new javax.swing.JTextArea();
        jTextFieldArquivoSelecionado = new javax.swing.JTextField();
        jLabelArquivo = new javax.swing.JLabel();
        jButtonExecutar = new javax.swing.JButton();
        jButtonBuscarArquivo = new javax.swing.JButton();
        jButtonParametros = new javax.swing.JButton();

        jFileChooser.setDialogTitle("Selecione um arquivo de vértices no formato .tsp");
        jFileChooser.setFileFilter(new FileFilterTxt());

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("AlgGen - PCV");
        setResizable(false);

        jTextArea.setEditable(false);
        jTextArea.setColumns(20);
        jTextArea.setLineWrap(true);
        jTextArea.setRows(5);
        jTextArea.setAutoscrolls(false);
        jTextArea.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(jTextArea);

        jTextFieldArquivoSelecionado.setEditable(false);

        jLabelArquivo.setText("Arquivo:");

        jButtonExecutar.setText("Executar");
        jButtonExecutar.setEnabled(false);
        jButtonExecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExecutarActionPerformed(evt);
            }
        });

        jButtonBuscarArquivo.setText("Buscar");
        jButtonBuscarArquivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarArquivoActionPerformed(evt);
            }
        });

        jButtonParametros.setText("Parâmetros");
        jButtonParametros.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonParametrosActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(33, 33, 33)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 443, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jButtonParametros)
                                .add(0, 0, Short.MAX_VALUE))
                            .add(layout.createSequentialGroup()
                                .add(jLabelArquivo)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(jTextFieldArquivoSelecionado, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 275, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jButtonBuscarArquivo, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jButtonExecutar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(38, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(25, 25, 25)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabelArquivo)
                    .add(jTextFieldArquivoSelecionado, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButtonBuscarArquivo))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonExecutar)
                    .add(jButtonParametros))
                .add(18, 18, 18)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
                .add(34, 34, 34))
        );

        jButtonParametros.getAccessibleContext().setAccessibleName("Config. parâmetros");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonExecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExecutarActionPerformed
        new Thread(() -> {
            try {
                File arquivo = new File(jTextFieldArquivoSelecionado.getText());
                jTextArea.setText(null);
                jButtonExecutar.setEnabled(false);
                jButtonParametros.setEnabled(false);

                AlgGeneticoCaixeiroViajante alg = new AlgGeneticoCaixeiroViajante();
                Solucao melhor = alg.executa(arquivo);

                jTextArea.setText(melhor.toString());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            } finally {
                jButtonExecutar.setEnabled(true);
                jButtonParametros.setEnabled(true);
            }
        }).start();
    }//GEN-LAST:event_jButtonExecutarActionPerformed

    private void jButtonBuscarArquivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarArquivoActionPerformed
        int returnVal = jFileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            arquivoSelecionado = jFileChooser.getSelectedFile();
            jTextFieldArquivoSelecionado.setText(arquivoSelecionado.getAbsolutePath());
            jButtonExecutar.setEnabled(true);
        }
    }//GEN-LAST:event_jButtonBuscarArquivoActionPerformed

    private void jButtonParametrosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonParametrosActionPerformed
        telaParametros.setVisible(true);
    }//GEN-LAST:event_jButtonParametrosActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
                javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(() -> {
            new TelaPrincipal().setVisible(true);
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBuscarArquivo;
    private javax.swing.JButton jButtonExecutar;
    private javax.swing.JButton jButtonParametros;
    private javax.swing.JFileChooser jFileChooser;
    private javax.swing.JLabel jLabelArquivo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea;
    private javax.swing.JTextField jTextFieldArquivoSelecionado;
    // End of variables declaration//GEN-END:variables
}

class FileFilterTxt extends javax.swing.filechooser.FileFilter {

    @Override
    public boolean accept(File file) {
        return (file.isDirectory() || file.getAbsolutePath().endsWith(".tsp"));
    }

    @Override
    public String getDescription() {
        return "Documentos de texto (*.tsp)";
    }
}
